<?php

function get_posts_by_index_on_homepage()
{
    if (!check_ajax_referer('zb_ajax', 'nonce', false)) {
        wp_send_json(array(
            'status' => 0,
            'msg'    => __('非法请求', 'ripro'),
        ));
    }

    $index = get_param('index');
    $widget_options = get_option('widget_ri_home_ajax_posts_widget');
    $category_and_posts = $widget_options[2]["category_and_posts"];
    $posts = $category_and_posts[$index]['posts'];
    $post_ids = explode(',', $posts);

    $query_args = array(
        'ignore_sticky_posts' => false,
        'post_status'         => 'publish',
        'post__in' => $post_ids,
        'posts_per_page'      => 8,
    );

    $PostData = new WP_Query($query_args);

    $empty_posts = [];

    if(!empty($PostData->posts)){
        foreach($PostData->posts as $post){
            $empty_posts[] = ['post_title' => $post->post_title,
                'featured_image' => get_the_post_thumbnail_url($post->ID),
                'post_categories' => get_category_list($post->ID),
                'post_permalink' => $post->guid,
                'post_excerpt' => $post->post_excerpt];
        }
    }

    wp_send_json(array(
        'status' => 0,
        'msg'    => __('请登录后购买', 'ripro'),
        'data' => $empty_posts
    ));
}

add_action('wp_ajax_nopriv_get_posts_by_index_on_homepage', 'get_posts_by_index_on_homepage');

function get_category_list($post_id)
{
    $category_list = [];
    foreach(get_the_category($post_id) as $category){
        $category_list[] = ['slug' => $category->slug, 'name' => $category->cat_name];
    }
    return $category_list;
}